<template>
  <div class="personnel-passage-record bg-background text-foreground p-4">
    <h2 class="mb-4 text-2xl font-bold">人员通行记录</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">

      <query-form :model="search" :formItems="formItems" @search="searchPersonnel" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
      <button @click="confirmDelete" class="btn btn-destructive">删除</button>
      <button @click="openImportDialog" class="btn btn-secondary">导入</button>
      <button @click="exportData" class="btn btn-secondary">导出</button> -->
      <!-- <el-button class="btn" type="primary" @click="openAddDialog" style="width: 75px; height: 30px;">新增</el-button>
      <el-button class="btn" @click="confirmDelete" style="width: 75px; height: 30px;">删除</el-button> -->
      <!-- <el-button @click="openImportDialog" style="width: 75px; height: 30px;">导入</el-button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPersonnelData" style="width: 100%"
        @selection-change="handleSelectionChange" ref="table" align="center" class="data-table"
        :header-cell-style="headerCellStyle">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <!-- <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndex + scope.$index + 1 }}
          </template>
</el-table-column> -->
        <el-table-column prop="EQUIPMENT_CODE" label="设备编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_CODE" label="人员编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_NAME" label="人员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STAFF_TYPE" label="人员类型" header-align="center" align="center">
          <template #default="scope">
            {{ getStaffTypeText(scope.row.STAFF_TYPE) }}
          </template>
        </el-table-column>
        <el-table-column prop="PASS_TIME" label="通行时间" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.PASS_TIME) }}
          </template>
        </el-table-column>
        <el-table-column prop="PASS_TYPE" label="通行类型" header-align="center" align="center">
          <template #default="scope">
            {{ getPassageTypeText(scope.row.PASS_TYPE) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="通行抓拍" header-align="center" align="center">
          <template #default="scope">
            <span v-if="!scope.row.imgdata">暂无图片</span>
            <el-image v-else style="width: 100px; height: 100px" lazy :src="scope.row.imgdata" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="loadRecordForUpdate(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div class="bg-card text-card-foreground border-border flex items-center justify-between border-t px-4 py-3 sm:px-6">
      <!-- <div class="flex items-center">
        <span class="mr-2">每页显示</span>
        <select v-model="pageSize" @change="changePageSize"
          class="rounded border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
          <option :value="10">10</option>
          <option :value="20">20</option>
          <option :value="50">50</option>
        </select>
        <span class="ml-2">条</span>
      </div>
      <div class="flex items-center">
        <button @click="prevPage" :disabled="currentPage === 1"
          class="mr-1 rounded bg-gray-200 px-3 py-1 text-gray-700">
          &lt;
        </button>
        <button v-for="page in displayedPages" :key="page" @click="goToPage(page)" :class="[
          'px-3',
          'py-1',
          'rounded',
          'mr-1',
          currentPage === page
            ? 'bg-blue-500 text-white'
            : 'bg-gray-200 text-gray-700',
        ]">
          {{ page }}
        </button>
        <button @click="nextPage" :disabled="currentPage === totalPages"
          class="ml-1 rounded bg-gray-200 px-3 py-1 text-gray-700">
          &gt;
        </button>
        <span class="ml-2">跳至</span>
        <input v-model.number="jumpToPage" @keyup.enter="goToPage(jumpToPage)" type="number" min="1" :max="totalPages"
          class="mx-2 w-16 rounded border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
        <span>页</span>
      </div> -->
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>

    <!-- Add Personnel Dialog -->
    <!-- <Teleport to="body">
      <div v-if="isAddDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">
              {{ editingItem ? '编辑人员通行记录' : '新增人员通行记录' }}
            </h3>
            <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <form @submit.prevent="handleSubmit">
            表单字段
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="newEquipmentCode" class="block text-sm font-medium text-gray-700">设备编码：</label>
                <input type="text" id="newEquipmentCode" v-model="newRecord.EQUIPMENT_CODE" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
              </div>
              <div>
                <label for="newStaffCode" class="block text-sm font-medium text-gray-700">人员编码：</label>
                <input type="text" id="newStaffCode" v-model="newRecord.STAFF_CODE" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
              </div>
              <div>
                <label for="newStaffName" class="block text-sm font-medium text-gray-700">人员姓名：</label>
                <input type="text" id="newStaffName" v-model="newRecord.STAFF_NAME" placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
              </div>
              <div>
                <label for="newStaffType" class="block text-sm font-medium text-gray-700">人员类型：</label>
                <select id="newStaffType" v-model="newRecord.STAFF_TYPE"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                  <option value="">请选择</option>
                  <option value="0">备案人员</option>
                  <option value="1">访客人员</option>
                </select>
              </div>
              <div>
                <label for="newPassTime" class="block text-sm font-medium text-gray-700">通行时间：</label>
                <input type="datetime-local" id="newPassTime" v-model="newRecord.PASS_TIME"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
              </div>
              <div>
                <label for="newPassType" class="block text-sm font-medium text-gray-700">通行类型：</label>
                <select id="newPassType" v-model="newRecord.PASS_TYPE"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                  <option value="">请选择</option>
                  <option value="in">进</option>
                  <option value="out">出</option>
                </select>
              </div>
              <div>
                <label
                  for="newCreateBy"
                  class="block text-sm font-medium text-gray-700"
                  >创建人：</label
                >
                <input
                  type="text"
                  id="newCreateBy"
                  v-model="newRecord.CREATE_BY"
                  placeholder="请输入"
                  class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                />
              </div>
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button type="button" @click="closeAddDialog" class="btn btn-secondary">
                取消
              </button>
              <button type="submit" class="btn btn-primary">确认</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport> -->
    <el-dialog class="dialog-from" v-model="isAddDialogOpen" :title="isDialogType == 'add' ? '人员通行记录新增' : '人员通行记录编辑'"
      width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="newRecord" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="设备编码：" label-position="top" prop="EQUIPMENT_CODE">
                  <el-input v-model="newRecord.EQUIPMENT_CODE" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="人员编码：" label-position="top" prop="STAFF_CODE">
                  <el-input v-model="newRecord.STAFF_CODE" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="人员姓名：" label-position="top" prop="STAFF_NAME">
                  <el-input v-model="newRecord.STAFF_NAME" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="人员类型：" label-position="top" prop="STAFF_TYPE">
                  <el-select v-model="newRecord.STAFF_TYPE" placeholder="请选择" clearable>
                    <el-option label="备案人员" value="1" />
                    <el-option label="访客人员" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通行时间：" label-position="top" prop="PASS_TIME">
                  <input type="datetime-local" id="newPassTime" v-model="newRecord.PASS_TIME"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通行类型：" label-position="top" prop="PASS_TYPE">
                  <el-select v-model="newRecord.PASS_TYPE" placeholder="请选择" clearable>
                    <el-option label="进" value="in" />
                    <el-option label="出" value="out" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="通行抓拍：" label-position="top" prop="PASS_IMG">
                  <div style="display: flex;">
                    <div v-if="newRecord.imgdata">
                      <el-image style="width: 100px; height: 100px" lazy :src="newRecord.imgdata" fit="cover" />
                    </div>
                    <el-upload :auto-upload="false" class=" upload-demo" action="#" :on-change="handleChange"
                      :show-file-list="false">
                      <div>
                        <span class="attachment-text">附件</span>
                        <el-input v-model="newRecord.PASS_IMG" placeholder="点击上传文件" readonly class="input-upload" />
                      </div>
                    </el-upload>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确认</el-button>
          <el-button @click="closeAddDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Import Dialog -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <h3 class="mb-4 text-lg font-bold">导入人员通行记录</h3>
          <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
            class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
          <div class="flex justify-end space-x-2">
            <button @click="closeImportDialog" class="btn btn-secondary">
              取消
            </button>
            <button @click="importData" class="btn btn-primary">导入</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- View Details Dialog -->
    <!-- <Teleport to="body">
      <div v-if="isViewDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">查看人员通行记录详情</h3>
            <button @click="closeViewDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <div v-if="selectedItem">
            <p><strong>设备编码：</strong>{{ selectedItem.EQUIPMENT_CODE }}</p>
            <p><strong>人员编码：</strong>{{ selectedItem.STAFF_CODE }}</p>
            <p><strong>人员姓名：</strong>{{ selectedItem.STAFF_NAME }}</p>
            <p>
              <strong>人员类型：</strong>{{ getStaffTypeText(selectedItem.STAFF_TYPE) }}
            </p>
            <p><strong>通行时间：</strong>{{ selectedItem.PASS_TIME }}</p>
            <p>
              <strong>通行类型：</strong>{{ getPassageTypeText(selectedItem.PASS_TYPE) }}
            </p>
            <p><strong>备注：</strong>{{ selectedItem.REMARKS }}</p>
            <div v-if="selectedItem.PASS_IMG">
              <p><strong>通行抓拍：</strong></p>
              <img :src="selectedItem.PASS_IMG" alt="通行抓拍" class="mt-4 h-auto w-full" />
            </div>
            <p v-else><strong>通行抓拍：</strong>无抓拍</p>
          </div>
          <div class="mt-4 flex justify-end">
            <button @click="closeViewDialog" class="btn btn-secondary">
              关闭
            </button>
          </div>
        </div>
      </div>
    </Teleport> -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="人员通行记录详情" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="设备编码：">{{ selectedItem.EQUIPMENT_CODE }}</el-descriptions-item>
            <el-descriptions-item label="人员编码：">{{ selectedItem.STAFF_CODE }}</el-descriptions-item>
            <el-descriptions-item label="人员姓名：">{{ selectedItem.STAFF_NAME }}</el-descriptions-item>
            <el-descriptions-item label="人员类型：">{{ getStaffTypeText(selectedItem.STAFF_TYPE) }}</el-descriptions-item>
            <el-descriptions-item label="通行时间：">{{ formatDateTime(selectedItem.PASS_TIME) }}</el-descriptions-item>
            <el-descriptions-item label="通行类型：">{{ getPassageTypeText(selectedItem.PASS_TYPE) }}</el-descriptions-item>
            <el-descriptions-item label="通行抓拍：">
              <div v-if="selectedItem.PASS_IMG == null
                ">
                {{ selectedItem.PASS_IMG ? selectedItem.PASS_IMG : '无'
                }}
              </div>
              <el-image v-else style="width: 100px; height: 100px" lazy :src="selectedItem.imgdata" :zoom-rate="1.2"
                :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addExpert">确认</el-button>
          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template> -->
    </el-dialog>


    <!-- Edit Dialog -->
    <!-- <Teleport to="body">
      <div v-if="updateData.id"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">编辑人员记录</h3>
            <button @click="resetUpdateData" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="updateEquipmentCode" class="text-muted-foreground block text-sm font-medium">设备编码：</label>
              <input type="text" id="updateEquipmentCode" v-model="updateData.EQUIPMENT_CODE"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
            </div>
            <div>
              <label for="updateStaffCode" class="text-muted-foreground block text-sm font-medium">人员编码：</label>
              <input type="text" id="updateStaffCode" v-model="updateData.STAFF_CODE"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
            </div>
            <div>
              <label for="updateStaffName" class="text-muted-foreground block text-sm font-medium">人员姓名：</label>
              <input type="text" id="updateStaffName" v-model="updateData.STAFF_NAME"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
            </div>
            <div>
              <label for="updateStaffType" class="text-muted-foreground block text-sm font-medium">人员类型：</label>
              <select id="updateStaffType" v-model="updateData.STAFF_TYPE"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                <option value="">请选择</option>
                <option value="0">备案人员</option>
                <option value="1">访客人员</option>
              </select>
            </div>
            <div>
              <label for="updatePassTime" class="text-muted-foreground block text-sm font-medium">通行时间：</label>
              <input type="datetime-local" id="updatePassTime" v-model="updateData.PASS_TIME"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
            </div>
            <div>
              <label for="updatePassType" class="text-muted-foreground block text-sm font-medium">通行类型：</label>
              <select id="updatePassType" v-model="updateData.PASS_TYPE"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                <option value="">请选择</option>
                <option value="in">进</option>
                <option value="out">出</option>
              </select>
            </div>
            <div>
              <label for="updatePassImg" class="text-muted-foreground block text-sm font-medium">通行抓拍：</label>
              <div class="mt-1 flex items-center">
                <input type="file" id="updatePassImg" @change="handleUpdatePhotoUpload" accept="image/*"
                  class="sr-only" />
                <label for="updatePassImg"
                  class="bg-secondary text-secondary-foreground hover:bg-secondary/80 focus:ring-secondary cursor-pointer rounded-md px-3 py-2 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-offset-2">
                  更新附件
                </label>
                <span class="text-muted-foreground ml-2 text-sm">{{
                  updateData.PASS_IMG ? '已选择文件' : '未选择文件'
                }}</span>
              </div>
            </div>
            <div>
              <label
                for="updateBy"
                class="text-muted-foreground block text-sm font-medium"
                >更新人：</label
              >
              <input
                type="text"
                id="updateBy"
                v-model="updateData.UPDATE_BY"
                class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1"
              />
            </div>
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button @click="resetUpdateData" class="btn btn-secondary">
              取消
            </button>
            <button @click="updateRecord" class="btn btn-primary">确认</button>
          </div>
        </div>
      </div>
    </Teleport> -->
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/personnel-pass')

const search = ref({
  STAFF_CODE: '',
  STAFF_NAME: '',
  STAFF_TYPE: '',
  PASS_TYPE: '',
})
const formItems = ref([
  {
    label: '人员编码：',
    model: 'STAFF_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员姓名：',
    model: 'STAFF_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员类型：',
    model: 'STAFF_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: '备案人员', value: '0' },
      { label: '访客人员', value: '1' },
    ],
  },
  {
    label: '通行类型：',
    model: 'PASS_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: '进', value: 'in' },
      { label: '出', value: 'out' },
    ],
  },
])
const editingItem = ref(false)
const personnelData = ref([])
const uploadedImage = ref('')
const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const importFile = ref(null)
const newRecord = ref({
  EQUIPMENT_CODE: '',
  STAFF_CODE: '',
  STAFF_NAME: '',
  STAFF_TYPE: '',
  PASS_TIME: '',
  PASS_TYPE: '',
  PASS_IMG: '',
  files: []
})
const recordId = ref('')
const currentRecord = ref(null)
const updateData = ref({
  ID: '',
  EQUIPMENT_CODE: '',
  STAFF_CODE: '',
  STAFF_NAME: '',
  STAFF_TYPE: '',
  PASS_TIME: '',
  PASS_TYPE: '',
  PASS_IMG: '',
})
const deleteId = ref('')
const deleteUpdateBy = ref('')
const selectedItem = ref(null)

const allRecords = ref([])

const totalItems = computed(() => allRecords.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)
const endIndex = computed(() =>
  Math.min(startIndex.value + pageSize.value, totalItems.value),
)
const displayedPages = computed(() => {
  const range = 2
  const start = Math.max(1, currentPage.value - range)
  const end = Math.min(totalPages.value, currentPage.value + range)
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

const getStaffTypeText = (type) => {
  switch (type) {
    case '0':
      return '备案人员'
    case '1':
      return '访客人员'
    default:
      return type || ''
  }
}

// const filteredPersonnelData = computed(() => {
//   return personnelData.value
//     .filter(
//       (item) =>
//         item.STAFF_CODE.toLowerCase().includes(
//           search.value.personnelCode.toLowerCase(),
//         ) &&
//         (item.STAFF_NAME || '')
//           .toLowerCase()
//           .includes(search.value.personnelName.toLowerCase()) &&
//         (search.value.personnelType === '' ||
//           item.STAFF_TYPE === search.value.personnelType) &&
//         (search.value.passageType === '' ||
//           item.PASS_TYPE === search.value.passageType),
//     )
//     .map((item) => ({
//       ...item,
//       STAFF_TYPE_TEXT: getStaffTypeText(item.STAFF_TYPE),
//       selected: item.selected, // 确保保留 selected 属性
//     }));
// });

const displayedPersonnelData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  // return filteredPersonnelData.value.slice(start, end);
  return allRecords.value.slice(start, end)
})


// const searchPersonnel = () => {
//   // currentPage.value = 1;
//   // getAllRecords();
// };
const searchPersonnel = async () => {
  try {
    loading.value = true
    // const response = await axios.get(`${apiBaseUrl.value}/search`, {
    //   params: search.value,
    // })
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    allRecords.value = (await Promise.all(response.data.map(async (item) => {

      if (item.PASS_IMG != null && item.PASS_IMG != '') {
        const resimg = await axios.get(`${apiBaseUrl.value}/download/${item.PASS_IMG}`)
        return { ...item, checked: false, imgdata: resimg.data.url }
      } else {
        return { ...item, checked: false, imgdata: item.PASS_IMG }
      }
    })))




    // allRecords.value = response.data
    currentPage.value = 1
    selectedIds.value = []
    loading.value = false
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const resetSearch = () => {
  search.value = {
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    PASS_TYPE: '',
  }
  // currentPage.value = 1;
  searchPersonnel()
}

const openAddDialog = () => {
  isAddDialogOpen.value = true
  isDialogType.value = 'add'
  newRecord.value = {
    EQUIPMENT_CODE: '',
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: '',
    CREATE_BY: '',
    files: []
  }
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  newRecord.value = {
    EQUIPMENT_CODE: '',
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: '',
    files: []
  }
}

const handlePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    newRecord.value.PASS_IMG = file
  }
}

// 添加这些辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const formatDateTimeForAPI = (dateTimeString) => {
  if (!dateTimeString) return null
  const date = new Date(dateTimeString)
  return date.toISOString() // 格式化为 ISO 8601 格式
}

// 修改 addNewPersonnel 函数
const addNewPersonnel = async () => {
  try {
    const newPersonnelData = {
      EQUIPMENT_CODE: newRecord.value.EQUIPMENT_CODE,
      STAFF_CODE: newRecord.value.STAFF_CODE,
      STAFF_NAME: newRecord.value.STAFF_NAME,
      STAFF_TYPE: newRecord.value.STAFF_TYPE,
      PASS_TIME: formatDateTimeForAPI(newRecord.value.PASS_TIME),
      PASS_TYPE: newRecord.value.PASS_TYPE,
      CREATE_BY: newRecord.value.CREATE_BY,
    }

    // 如果有图片文件，需要单独处理
    if (newRecord.value.PASS_IMG instanceof File) {
      const formData = new FormData()
      formData.append('file', newRecord.value.PASS_IMG)

      // 先上传图片
      const uploadResponse = await axios.post(
        `${apiBaseUrl.value}/upload`,
        formData,
        {
          headers: { 'Content-Type': 'multipart/form-data' },
        },
      )

      // 假设后端返回上传后的图片URL
      newPersonnelData.PASS_IMG = uploadResponse.data.url
    }

    // 发送新增人员数据
    const response = await axios.post(apiBaseUrl.value, newPersonnelData)

    console.log('Response:', response.data)
    alert(response.data.message || '创建记录成功')
    resetNewRecord()
    await searchPersonnel()
    closeAddDialog()
  } catch (error) {
    console.error('创建记录失败:', error)
    if (error.response) {
      console.error('Error response:', error.response.data)
    }
    alert('创建记录失: ' + (error.response?.data?.message || error.message))
  }
}

const resetNewRecord = () => {
  newRecord.value = {
    EQUIPMENT_CODE: '',
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: '',
    CREATE_BY: '',
    files: []
  }
}

const getAllRecords = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: search.value,
    })
    allRecords.value = response.data.map((alarm) => ({
      ...alarm,
      selected: false,
    }))
    personnelData.value = allRecords.value.map((item) => ({
      ...item,
      selected: false, // 确保每个项目都有 selected 属性
    }))
    updateSelectAllState() // 更新全选状态
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const handleSubmit = () => {
  try {


    formRef.value.validate(async (valid) => {
      if (valid) {
        const formData = new FormData()
        for (const key in newRecord.value) {
          if (key !== 'files') {
            formData.append(key, newRecord.value[key])
          }
        }
        if (newRecord.value?.files) {
          newRecord.value.files.forEach((file, index) => {
            formData.append(`files[${index}]`, file)
          })
        }
        // console.log('newRecord.value', newRecord.value)

        // const response = await axios.post(apiBaseUrl.value, newRecord.value)
        const response = await axios.put(apiBaseUrl.value + '/' + newRecord.value.ID, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        // console.log('Response:', response)
        alert(response.data.message || '创建人员通行记录成功')
        closeAddDialog()
        await searchPersonnel()
      }
    })

    // allRecords.value = response.data.map((alarm) => ({
    //   ...alarm,
    //   selected: false,
    // }));
    // personnelData.value = allRecords.value.map((item) => ({
    //   ...item,
    //   selected: false, // 确保每个项目都有 selected 属性
    // }))
    // updateSelectAllState(); // 更新全选状态
  } catch (error) {
    console.log(error)
    console.error('创建人员通行记录失败:', error)
    alert(
      '创建人员通行记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const updatePassType = (value) => {
  if (value === '0') {
    return 'in'
  } else {
    return 'out'
  }
}
// 修改 loadRecordForUpdate 函数
const loadRecordForUpdate = (record) => {
  newRecord.value = {
    ID: record.ID,
    EQUIPMENT_CODE: record.EQUIPMENT_CODE,
    STAFF_CODE: record.STAFF_CODE,
    STAFF_NAME: record.STAFF_NAME,
    STAFF_TYPE: record.STAFF_TYPE,
    PASS_TIME: formatDateTimeForInput(record.PASS_TIME),
    PASS_TYPE: updatePassType(record.PASS_TYPE),
    PASS_IMG: record.PASS_IMG,
    imgdata: record.imgdata
  }
  isDialogType.value = 'edit'
  isAddDialogOpen.value = true
  console.log('loadRecordForUpdate', newRecord.value)
}

const confirmDelete = () => {
  deleteRecord()
  // if (confirm('确定要删除这条记录吗？')) {
  //   deleteId.value = ID;
  //   // deleteUpdateBy.value = prompt('请输入更新人:');
  //   if (deleteUpdateBy.value) {
  //   }
  // }
}
const selectedIds = ref([])
const deleteRecord = async () => {
  // if (!deleteId.value || !deleteUpdateBy.value) {
  //   alert('请输入记录ID和更新人');
  //   return;
  // }
  if (selectedIds.length === 0) {
    alert('请选择要删除的设备')
    return
  }
  // const deleteIds = ref([])
  // selectedIds.value.forEach((item) => {
  //   console.log('111', item.ID)
  //   // deleteIds.push
  // })
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 个设备吗？`)) {
    console.log(selectedIds.value)
    try {
      await Promise.all(
        selectedIds.value.map((item) =>
          axios.delete(`${apiBaseUrl.value}/${item.ID}`),
        ),
      )
      alert('删除成功')
      selectedIds.value = []
      await searchPersonnel()
    } catch (error) {
      console.error('删除设备失败:', error)
      alert('删除设备失败: ' + (error.response?.data?.message || error.message))
    }
  }
  // try {
  //   const response = await axios.delete(
  //     `${apiBaseUrl.value}/${ID}`,
  //     {
  //       data: { UPDATE_BY: deleteUpdateBy.value },
  //     },
  //   );
  //   // console.log('Delete response:', response.data);
  //   alert(response.data.message || '删除记录成功');
  //   deleteId.value = '';
  //   deleteUpdateBy.value = '';
  //   await getAllRecords();
  // } catch (error) {
  //   console.error('删除记录失败:', error);
  //   if (error.response) {
  //     console.error('Error response:', error.response.data);
  //   }
  //   alert('删除记录失败: ' + (error.response?.data?.message || error.message));
  // }
}

const getRecord = async () => {
  if (!recordId.value) {
    alert('请输入记录ID')
    return
  }
  try {
    const response = await axios.get(`${apiBaseUrl.value}/${recordId.value}`)
    currentRecord.value = response.data
  } catch (error) {
    console.error('获取记录失败:', error)
    alert('获取记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 修改 updateRecord 函数
const updateRecord = async () => {
  try {
    const updatePayload = {
      EQUIPMENT_CODE: updateData.value.EQUIPMENT_CODE,
      STAFF_CODE: updateData.value.STAFF_CODE,
      STAFF_NAME: updateData.value.STAFF_NAME,
      STAFF_TYPE: updateData.value.STAFF_TYPE.toString(),
      PASS_TIME: formatDateTimeForAPI(updateData.value.PASS_TIME),
      PASS_IMG: updateData.value.PASS_IMG,
      PASS_TYPE: updateData.value.PASS_TYPE,
    }

    if (updateData.value.PASS_IMG instanceof File) {
      const formData = new FormData()
      formData.append('file', updateData.value.PASS_IMG)

      const uploadResponse = await axios.post(
        `${apiBaseUrl.value}/upload`,
        formData,
        {
          headers: { 'Content-Type': 'multipart/form-data' },
        },
      )

      updatePayload.PASS_IMG = uploadResponse.data.url
    } else if (typeof updateData.value.PASS_IMG === 'string') {
      updatePayload.PASS_IMG = updateData.value.PASS_IMG
    }

    console.log('Updating with data:', updatePayload)
    console.log(
      'Sending update request to:',
      `${apiBaseUrl.value}/${updateData.value.ID}`,
    )

    const response = await axios.put(
      `${apiBaseUrl.value}/${updateData.value.ID}`,
      updatePayload,
    )

    console.log('Update response:', response.data)

    alert(response.data.message || '更新记录成功')
    resetUpdateData()
    await searchPersonnel()
  } catch (error) {
    console.error('更新记录失败:', error)
    if (error.response) {
      console.error('Error response:', error.response.data)
    }
    alert('更新记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetUpdateData = () => {
  updateData.value = {
    ID: '',
    EQUIPMENT_CODE: '',
    STAFF_CODE: '',
    STAFF_NAME: '',
    STAFF_TYPE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: '',
    UPDATE_BY: '',
  }
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  personnelData.value.forEach((item) => (item.selected = selectAll.value))
}

const toggleItemSelection = (item) => {
  // item.selected = !item.selected;
  // updateSelectAllState();
  const index = selectedIds.value.indexOf(item.ID)
  if (index === -1) {
    selectedIds.value.push(item.ID)
  } else {
    selectedIds.value.splice(index, 1)
  }
  selectAll.value = selectedIds.value.length === allRecords.value.length
}

const updateSelectAllState = () => {
  selectAll.value =
    personnelData.value.length > 0 &&
    personnelData.value.every((item) => item.selected)
}

const deleteSelected = async () => {
  const selectedItems = personnelData.value.filter((item) => item.selected)

  if (selectedItems.length === 0) {
    alert('请至少选择一条记录进行删除')
    return
  }

  if (!confirm(`确定要���除选中的 ${selectedItems.length} 条记录吗？`)) {
    return
  }

  const deleteUpdateBy = prompt('请输入更新人:')
  if (!deleteUpdateBy) {
    return
  }

  try {
    const deletePromises = selectedItems.map((item) =>
      axios.delete(`${apiBaseUrl.value}/${item.ID}`, {
        data: { UPDATE_BY: deleteUpdateBy },
      }),
    )

    const results = await Promise.allSettled(deletePromises)

    const successCount = results.filter(
      (result) => result.status === 'fulfilled',
    ).length
    const failCount = results.length - successCount

    if (failCount === 0) {
      alert(`成功删除 ${successCount} 条记录`)
    } else {
      alert(`成功删除 ${successCount} 条记录，${failCount} 条记录删除失败`)
    }

    await searchPersonnel()
    updateSelectAllState() // 更新全选状态
  } catch (error) {
    console.error('批量删除记录失败:', error)
    alert(
      '批量删除记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = async () => {
  if (!importFile.value) {
    alert('请��择要导入的文件')
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)

    try {
      console.log('导入数据 - 发送数据:', jsonData)
      const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
      console.log('导入数据 - 接收到的响应:', response.data)
      alert('数据导入成功')
      closeImportDialog()
      await searchPersonnel()
    } catch (error) {
      console.error('Error importing data:', error)
      alert('导入数据失败：' + error.message)
    }
  }
  reader.readAsArrayBuffer(importFile.value)
}

const exportData = () => {
  const dataToExport = allRecords.value.map((item) => ({
    设备编码: item.EQUIPMENT_CODE,
    人员编码: item.STAFF_CODE,
    人员姓名: item.STAFF_NAME,
    人员类型: getStaffTypeText(item.STAFF_TYPE),
    通行时间: formatDateTime(item.PASS_TIME),
    通行类型: getPassageTypeText(item.PASS_TYPE),
    // 通行抓拍: getPassageTypeText(item.PASS_IMG),
  }))
  console.log('111', dataToExport)
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '人员通行记录')

  // 生成二进制字符串作为文件内容
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为Blob对象
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '人员通行记录.xlsx'
  link.click()
}

// 辅助函数：将字符串转换为ArrayBuffer
function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}

const viewDetails = (item) => {
  selectedItem.value = { ...item } // 创建一个新对象以避免引用问题
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = null
}

const changePageSize = () => {
  currentPage.value = 1
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

watch(selectAll, (newValue) => {
  personnelData.value.forEach((item) => (item.selected = newValue))
})

// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rules = {
  EQUIPMENT_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  STAFF_CODE: [
    { required: true, message: '请输入人员编码', trigger: 'blur' },
  ],
  STAFF_NAME: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' },
  ],
  STAFF_TYPE: [
    { required: true, message: '请输入人员类型', trigger: 'change' },
  ],
  PASS_TIME: [
    { required: true, message: '请输入通行时间', trigger: 'change' },
  ],
  PASS_TYPE: [
    { required: true, message: '请输入通行类型', trigger: 'change' },
  ],
}
const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const handleChange = (file, fileList) => {
  // 处理文件上传后的逻辑
  newRecord.value.files = [file.raw]
  newRecord.value.PASS_IMG = file.name // 这里可以根据需要调整

}

onMounted(() => {
  searchPersonnel()
})

// 修改按钮样式的计算属性
const btnClasses = computed(() => {
  return 'px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out'
})

const btnPrimaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-primary text-primary-foreground hover:bg-primary/90',
  ]
})
const handleUpdatePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    newRecord.value.PASS_IMG = file
    // updateData.value.PASS_IMG = file;
  }
}

const btnSecondaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-secondary text-secondary-foreground hover:bg-secondary/80',
  ]
})

const btnDestructiveClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-destructive text-destructive-foreground hover:bg-destructive/90',
  ]
})

// 1. 添加通行类型转换函数
const getPassageTypeText = (type) => {
  switch (type) {
    case '0':
      return '进'
    case '1':
      return '出'
    default:
      return type || ''
  }
}
</script>

<style scoped>
/* 移除大部分样式，因为现在由 Tailwind 类处理 */
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  /* height: 100px; */
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
